<template>
  <section>
    <!-- 工具条：高级查询 + 添加 -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="queryParams">
        <el-form-item>
          <!--
            el-input -- 输入框
               v-model="queryParams.keyword"    -- 双向绑定
               placeholder="姓名"               -- 提示语
            el-button -- 按钮
              type="primary"                    -- 颜色
              v-on:click="queryBykeyword"       -- 绑定单击事件
          -->
          <el-input v-model="queryParams.keyword" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="queryBykeyword">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!-- 分页列表 -->
    <el-table :data="pageParams.products" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="40">
      </el-table-column>
      <el-table-column prop="name" label="服务名称" width="150" sortable>
      </el-table-column>
      <el-table-column prop="resources" label="资源" width="300" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本" width="60" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" width="60" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="140" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="140" sortable>
      </el-table-column>
      <el-table-column label="状态" width="80">
        <template scope="scope">
          <!-- scope.row.state
            通过scope.row获取当前行的对象 = json对象
           -->
          <span style="color: #11b95c" v-if="scope.row.state==1">启用</span>
          <span style="color: red" v-else>禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="130" sortable>
      </el-table-column>
      <el-table-column prop="salecount" label="售卖量" width="130" sortable>
      </el-table-column>

      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 工具条：批量删除 + 分页栏 -->
    <el-col :span="24" class="toolbar">
      <!--
          :disabled="this.sels.length===0" - 至少选中一行，才可以点击
      -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="queryParams.pageSize" :total="pageParams.totals" :current-page="queryParams.currentPage" style="float:right;">
      </el-pagination>
    </el-col>
    <!-- 新增编辑模态框 -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="资源" prop="resources">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="成本价">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售卖价">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="服务简介">
          <quill-editor v-model="saveForm.productDetail.intro" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="服务须知1222222">
          <quill-editor v-model="saveForm.productDetail.orderNotice" :options="quillOption">
          </quill-editor>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>

//引入富文本编辑器
import { quillEditor } from "vue-quill-editor";
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
//富文本与fastDfs集成
import quillConfig from '../../common/js/quill-config.js'
export default {
  components: {
    quillEditor //使用富文本编辑器<quill-editor>
  },
  data() {
    return {
      //富文本集成fastDfs数据
      quillOption: quillConfig,
      //文件上传列表 - 资源resources
      fileList:[],
      //分页参数：分页列表 + 分页栏所需数据
      pageParams:{
        products: [],    //分页列表中：:data - 显示分页数据
        totals: 0           //总页数：分页栏中显示 - 计算分页栏的
      },

      //定义查询参数：分页查询 + 高级查询
      queryParams:{
        pageSize: 5,      //分页查询参数：每页显示的条数 or 分页栏中显示
        currentPage: 1,   //分页查询参数：当前页 or 分页栏中显示
        keyword: ''       //高级查询参数：关键字查询
      },

      //列表忙等框
      listLoading: false,
      //批量删除 - 保存选中的列
      sels: [],//列表选中列

      title:"保存", //添加和修改的模态框的标题
      saveFormVisible: false,//添加和修改的模态框默认不显示
      saveLoading: false, //保存模态框 - 默认不显示
      saveFormRules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        resources: null,
        costprice: null,
        saleprice: null,
        offsaletime: null,
        onsaletime: null,
        state: 1,//默认启用
        createtime: null,
        salecount: null,
        productDetail:{
          id: null,
          product_id: null,
          intro:null,
          orderNotice:null
        }
      },

    }
  },
  methods: {
    //上架
    onsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/product/onsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '上架成功',
              type: 'success'
            });
            this.getProducts();
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getProducts();
        });
      }).catch(() => {

      });
    },

    //下架
    offsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/product/offsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '下架成功',
              type: 'success'
            });
            this.getProducts();
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getProducts();
        });
      }).catch(() => {

      });
    },

    //高级查询 - ok
    queryBykeyword(){
      this.queryParams.currentPage = 1;
      this.getProducts();
    },

    //点击分页逻辑 - ok
    handleCurrentChange(val) {
      this.queryParams.currentPage = val;
      this.getProducts();
    },

    //获取服务分页列表 -ok
    getProducts() {
      this.listLoading = true; //显示忙等框
      this.$http.post("/product",this.queryParams)
          .then(res => {
            //成功之后的回调函数
            this.pageParams.totals = res.data.totals;
            this.pageParams.products = res.data.data;
            this.listLoading = false;//关闭忙等框
          }).catch(res => {
        this.$message.error('系统错误,请稍后重试1');
      })
    },
    
    //资源图片上传成功之后的处理
    handleSuccess(response, file, fileList){
      console.log("==========上传成功之后的回调========   ===")
      console.log(response); //response.resultObj
      console.log(file);
      console.log(fileList);

      //处理resources
      if(fileList!=null && fileList.length>0){//你上传了图片
        if(this.saveForm.resources){//如果以前有值
          this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
        }else{
          this.saveForm.resources = response.resultObj;
        }
      }

      //处理fileList
      if(resources){
        //   /group1/M00/00/72/rBEAA2BHkmaAbEOhAAEUusLjqqk505.png,/group1/M00/00/72/rBEAA2BHkmaAbEOhAAEUusLjqqk505.png
        var arr = resources.split(",");
        for(var i = 0; i<arr.length;i++){
          this.fileList.push({url:"http://47.95.117.210:8888" + arr[i]})
        }
      }
    },

    //资源图片点击删除时的处理
    handleRemove(file, fileList) {
      console.log("==========删除成功之后的回调===========");
      console.log(file);
      console.log(fileList);
      //从fastDfs删除文件
      var filePath =file.response.resultObj; // /group1/M00/01/F8/rBE3kWG3BjmAA9G5AAEUusLjqqk768.png
      this.$http.delete("/fastDfs/?path="+filePath).then(res=>{
        if(res.data.success){
          this.$message({
            message: '删除成功!',
            type: 'success'
          });
        }else{
          this.$message({
            message: '删除失败!',
            type: 'error'
          });
        }
      })
      //处理resources
      // /group1/M00/00/72/rBEAA2BHkmaAbEOhAAEUusLjqqk501.png,/group1/M00/01/F8/rBE3kWG3BjmAA9G5AAEUusLjqqk768.png,/group1/M00/00/72/rBEAA2BHkmaAbEOhAAEUusLjqqk505.png
      if(this.saveForm.resources){//有值
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          if(arr[i] == filePath){//找到删除的图片
            arr.splice(i,1);
          }
        }
        this.saveForm.resources = arr.join(",");
      }

      //处理fileList
      if(this.saveForm.resources){
        //   /group1/M00/00/72/rBEAA2BHkmaAbEOhAAEUusLjqqk505.png,/group1/M00/00/72/rBEAA2BHkmaAbEOhAAEUusLjqqk505.png
        var arr = this.saveForm.resources.split(",");
        for(var i = 0; i<arr.length;i++){
          this.fileList.push({url:"http://47.95.117.210:8888" + arr[i]})
        }
      }
    },

    //删除 - ok
    handleDel: function (index, row) {
      //确认框
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {  //点击确定之后的操作
        this.listLoading = true; //显示忙等框
        this.$http.delete("/product/" + row.id)
            .then(res => { //成功之后的回调
              this.listLoading = false; //关闭忙等框
              if(res.data.success){ //成功 200
                this.$message({   //删除成功之后的提示
                  message: "删除成功",
                  type: 'success'
                });
                this.getProducts();    //重新加载数据
              }else{ //500
                this.$message({   //删除成功之后的提示
                  message: res.data.msg,
                  type: 'error'
                });
              }
            }).catch(res => { //失败之后的回调
          this.$message.error('系统错误,请稍后重试');  //连不上后端代码或404，400
        })
      }).catch(() => {  //点击取消之后的操作
      });
    },
    //点击添加按钮弹出模态框
    handleAdd: function () {
      this.title = "添加";
      //重置
      this.saveForm = {
        id: null,
        name: null,
        resources: null,
        costprice: null,
        saleprice: null,
        state: 1, //默认启用
        productDetail: {
          intro: null,
          orderNotice: null
        }
      };
      //显示模态框
      this.saveFormVisible = true;
    },

    //点击编辑按钮弹出模态框
    handleEdit: function (index, row) {
      this.title = "修改";
      //克隆 - 回显
      this.saveForm = Object.assign({}, row);
      console.log(this.saveForm)
      //会显示详情

      this.$http.get("/product/detail/"+row.id).then(res=>{
        this.saveForm.productDetail = res.data;
        console.log(res.data)
        console.log(this.saveForm);
      });
      //图片回显
      this.fileList = [];
      var resources =  row.resources;
      if(resources){
        var resourcesArr = resources.split(",");
        for(var i=0;i<resourcesArr.length;i++){
          this.fileList.push({url:"http://47.95.117.210:8888"+resourcesArr[i]})
        }
      }
      this.saveFormVisible = true; //显示模态框
    },
    
    //点击保存按钮提交到后端
    saveSubmit: function () {
      //提交验证 - 只要表单验证不通过都不能提交
      this.$refs.saveForm.validate((valid) => {
        //如果验证通过返回true，返回返回false
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //显示忙等框
            this.saveLoading = true;

            //提交的数据
            let para = Object.assign({}, this.saveForm);
            console.log(this.saveForm)

            this.$http.put("/product",para).then(res => {
              this.saveLoading = false;//关闭忙等框
              if(res.data.success){
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                //重置表单
                this.$refs['saveForm'].resetFields();
                this.saveFormVisible = false; //关闭模态框
                this.getProducts();
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
                this.saveFormVisible = false; //关闭模态框
              }
            }).catch(res=>{
              this.$message.error('系统错误,请稍后重试');  //连不上后端代码或404，400
            })
          });
        }
      });
    },

    //批量删除 - 选中列的时候处罚 - ok
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除 - 真正的删除 -ok
    batchRemove: function () {
      //console.log(this.sels);//选中的行对象 - 集合
      //item - 就是集合中的每一个对象【json对象】
      var ids = this.sels.map(item => item.id);
      //console.log(this.sels.map(item => item.id));//[ 1, 2, 5, 7, 10 ]
      //console.log(ids);//1,2,5,7,10
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/product",ids)
            .then(res => {
              this.listLoading = false;
              if(res.data.success){
                this.$message({   //删除成功之后的提示
                  message: '删除成功',
                  type: 'success'
                });
                this.queryParams.currentPage = 1;//批量删除之后都到第一页
                this.getProducts();    //重新加载数据
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
              }
            }).catch(res => {
          this.$message.error('系统错误,请稍后重试');  //连不上后端代码或404
        })
      }).catch(() => { //点击取消之后的操作
      });
    }
  },
  mounted() {
    //页面一加载 - 获取分页数据
    this.getProducts();
  }
}

</script>

<style scoped>

</style>